package com.bootx.controller.api;

import com.bootx.common.Result;
import com.bootx.entity.OpenAiConfig;
import com.bootx.service.OpenAiConfigService;
import com.bootx.service.RedisService;
import jakarta.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/api")
public class IndexController {

    @Resource
    private RedisService redisService;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private OpenAiConfigService openAiConfigService;

    @PostMapping(value = "/setting")
    public Result setting(){
        Map<String,Object> map = new HashMap<>();
        String openParse = redisService.get("openParse");
        String predictCount = redisService.get("predictCount");
        String isRob = redisService.get("isRob");
        try {
            int i = Integer.parseInt(openParse);
            if(i==1){
                map.put("openParse",true);
            }else{
                map.put("openParse",false);
            }
        }catch (Exception e){
            map.put("openParse",false);
        }
        try {
            int i = Integer.parseInt(predictCount);
            map.put("predictCount",i);
        }catch (Exception e){
            map.put("predictCount",0);
        }
        try {
            int i = Integer.parseInt(isRob);
            if(i==1){
                map.put("isRob",true);
            }else{
                map.put("isRob",false);
            }
        }catch (Exception e){
            map.put("isRob",false);
        }
        map.put("predictType",redisService.get("predictType"));
        OpenAiConfig openAiConfig = openAiConfigService.find(1L);
        if (openAiConfig == null) {
            map.put("remainCount",0);
        }else{
            map.put("remainCount",openAiConfig.getRemainCount());
        }
        return Result.success(map);
    }

    @PostMapping(value = "/update")
    public Result update(Boolean openParse,Boolean isRob,Integer predictCount){
        if(openParse!=null && openParse){
            redisService.set("openParse","1");
        }else {
            redisService.set("openParse","0");
        }
        if(isRob!=null && isRob){
            redisService.set("isRob","1");
        }else {
            redisService.set("isRob","0");
        }
        if(predictCount!=null){
            redisService.set("predictCount",""+predictCount);
        }else {
            redisService.set("predictCount","50");
        }
        return Result.success();
    }

    @PostMapping(value = "/getData")
    public Result getData(){
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select win,result,amount, predictSeconds, predictIndex,redPackageCount,seconds,sn from redpackageinfo order by sn desc limit 1;");
        if(maps!=null && !maps.isEmpty()){
            redisService.set("stopTime", maps.getFirst().get("predictSeconds") + "");
            redisService.set("index", maps.getFirst().get("predictIndex") + "");
        }

        return Result.success(maps);
    }
    @PostMapping(value = "/result")
    public Result result(){
        return Result.success(jdbcTemplate.queryForList("select money, sn,isOdd,CASE win WHEN true then 1 WHEN false then 0 ELSE 100 END `win` from redpackageinfo order by sn desc;"));
    }
    @PostMapping(value = "/update1")
    public Result update1(Boolean win,String result,String sn){
        if(win){
            redisService.increment("win1");
            redisService.set("fail1","0");
            redisService.set("win",redisService.get("win1"));
            redisService.set("fail",redisService.get("fail1"));
        }else{
            redisService.increment("fail1");
            redisService.set("win1","0");
            redisService.set("win",redisService.get("win1"));
            redisService.set("fail",redisService.get("fail1"));
        }


        int update = jdbcTemplate.update("update redpackageinfo set win=?,result=? where sn=?", win, result, sn);
        if(update<=0){
          jdbcTemplate.update("insert into redpackageinfo(createdDate, lastModifiedDate, version, sn, win) value (NOW(),NOW(),0,?,?)",sn,win);
        }
        return Result.success();
    }

    @GetMapping(value = "/data")
    public Result data(Integer count) {
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select batchId `round` from (select batchId from redpackagestatistics order by batchId desc limit ?) AS X order by X.batchId asc", count);
        maps.forEach(map -> {
            List<Map<String, Object>> records = jdbcTemplate.queryForList("select orders `order`,FORMAT(money,2) `amount`,openTime from redpackage where batchId=? order by orders",map.get("round"));
            map.put("records",records);
            map.put("totalPeople",records.size());
            map.put("totalAmount",records.size()*0.5);
        });
        return Result.success(maps);
    }

    @PostMapping(value = "/remove")
    public Result remove(String sn) {
        jdbcTemplate.update("delete from redpackageinfo where sn=?", sn);
        return Result.success();
    }

    @PostMapping(value = "/upPredict")
    public Result upPredict(Integer type){
        redisService.set("predictType",type+"");
        return Result.success();
    }

    @PostMapping(value = "/clearData")
    public Result clearData(){
        jdbcTemplate.update("truncate redpackage;");
        jdbcTemplate.update("truncate redpackageinfo;");
        jdbcTemplate.update("truncate redpackagestatistics;");

        File file = new File("D:/red/fabaorenshu");
        File file1 = new File("D:/red/redpackage");
        Arrays.stream(Objects.requireNonNull(file.listFiles())).forEach(file2 -> {
            try {
                FileUtils.delete(file2);
            }catch (Exception ignored){}
        });
        Arrays.stream(Objects.requireNonNull(file1.listFiles())).forEach(file2 -> {
            try {
                FileUtils.delete(file2);
            }catch (Exception ignored){}
        });
        return Result.success();

    }
}
